package com.example.student.common;

import com.example.student.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常：{}", e.getMessage(), e);
        // 如果是登录相关的异常，使用UNAUTHORIZED状态码
        if (e.getMessage().contains("用户不存在") || 
            e.getMessage().contains("密码错误") || 
            e.getMessage().contains("账号已被禁用") || 
            e.getMessage().contains("账号已被锁定") ||
            e.getMessage().contains("认证失败")) {
            return Result.unauthorized(e.getMessage());
        }
        return Result.failed(e.getCode() != null ? e.getCode() : ResultCode.FAILED, e.getMessage());
    }

    /**
     * 处理认证异常
     */
    @ExceptionHandler(AuthenticationException.class)
    public Result<Void> handleAuthenticationException(AuthenticationException e) {
        log.error("认证异常：{}", e.getMessage(), e);
        String message = "认证失败";
        
        if (e instanceof BadCredentialsException) {
            message = "密码错误";
        } else if (e instanceof DisabledException) {
            message = "账号已被禁用";
        } else if (e instanceof LockedException) {
            message = "账号已被锁定";
        } else if (e instanceof UsernameNotFoundException) {
            message = "用户不存在";
        } else if (e.getMessage() != null) {
            if (e.getMessage().contains("Bad credentials")) {
                message = "密码错误";
            } else if (e.getMessage().contains("disabled")) {
                message = "账号已被禁用";
            } else if (e.getMessage().contains("locked")) {
                message = "账号已被锁定";
            } else if (e.getMessage().contains("expired")) {
                message = "登录已过期，请重新登录";
            }
        }
        
        return Result.unauthorized(message);
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Result<Void> handleValidException(Exception e) {
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        } else {
            bindingResult = ((BindException) e).getBindingResult();
        }

        StringBuilder message = new StringBuilder();
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            fieldErrors.forEach(error -> 
                message.append(error.getField())
                      .append(error.getDefaultMessage())
                      .append("; ")
            );
        }
        return Result.validateFailed(message.length() > 0 ? message.toString() : "参数验证失败");
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Result<Void> handleValidException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder message = new StringBuilder();
        violations.forEach(violation -> message.append(violation.getMessage()).append("; "));
        return Result.validateFailed(message.length() > 0 ? message.toString() : "参数验证失败");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("系统异常：{}", e.getMessage(), e);
        return Result.failed("系统异常，请联系管理员");
    }
} 